package task

import event.PastDueWaresChanged
import event.ReplenishErrorEvent
import ext.log
import manager.AppManager
import manager.NetworkManager
import mvc.model.inventory.GoodsTypeWare
import mvc.model.inventory.PastDueWare
import mvc.model.inventory.ScanModel
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject


class ReplenishTask(val infos: ArrayList<ScanModel>) : Runnable {

    private fun exec() {
        val array = JSONArray()
        infos.forEach {
            if (it.productionDate > 0) { // 格式错误的不上传到后台
                array.put(it.toJson())
            }
        }
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        json.put("array", array)
        val content = json.toString()
        log("--$content", "补货数据")
        val result = NetworkManager.replenishBybarCode(content)
        log("--$result", "补货返回")
        parse(JSONObject(result))
    }

    private fun parse(json: JSONObject) {
        val pastDue = json.getJSONArray("overdueArray")
        val length = pastDue.length()
        val pastDues = ArrayList<GoodsTypeWare>()
        for (i in 0 until length) {
            val empty = GoodsTypeWare.empty()
            empty.pastDueWare = PastDueWare.pastDueWithJson(pastDue.getJSONObject(i))
            pastDues.add(empty)
        }
        EventBus.getDefault().post(PastDueWaresChanged(pastDues))
    }

    override fun run() {
        try {
            exec()
        } catch (e: Exception) {
            e.printStackTrace()
            EventBus.getDefault().post(ReplenishErrorEvent())
        }
    }
}
